package com.chainyoung.component_tmperson.ui.activity.dapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chainyoung.common.appcommon.db.DbConstant;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.bus.AppManagerEvent;
import com.chainyoung.common.bus.RxBus;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.RxUtils;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.constant.PersonSystemConstant;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.entity.BrowseCache;
import com.chainyoung.component_tmperson.ui.adapter.BrowserHistoryAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.BrowserHistoryContract;
import com.chainyoung.component_tmperson.ui.mvp.model.dao.BrowseDAO;
import com.chainyoung.component_tmperson.ui.mvp.presenter.BrowserHistoryPresenter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.disposables.Disposable;
import io.reactivex.subscribers.ResourceSubscriber;

import static com.chainyoung.common.bus.AppManagerEvent.KILL_ALL;
import static com.chainyoung.common.constant.CommonStringConstants.URL;
import static com.chainyoung.common.utils.Utils.getAppComponent;

public class BrowserHistoryActivity extends BaseActivity<BrowserHistoryPresenter> implements BrowserHistoryContract.View {


    @BindView(R2.id.recycler_view)
    SwipeMenuRecyclerView recyclerView;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;


    private Disposable mDisposable;

    private BrowserHistoryAdapter mAdapter;

    private List<BrowseCache> mData = new ArrayList<>();

    private int removePos;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initUI() {
        setCurrentTitle("浏览记录");
        showAndSetBarRightText("清除所有");
        mAdapter = new BrowserHistoryAdapter();
        recyclerView.setAdapter(mAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });
        mAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) v.getTag();
                BrowseCache browseCache = mAdapter.getmListItems().get(p);
                Intent intent = new Intent(mContext, BrowserActivity.class);
                intent.putExtra(URL, browseCache.getUrl());
                startActivity(intent);
                finish();
            }
        });

        mAdapter.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final int p = (int) v.getTag();
                final BrowseCache browseCache = mAdapter.getmListItems().get(p);
                removePos = p;
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(mContext);
                builder.setMessage(R.string.tmperson_confirm_del_history_record)
                        .setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.delSingleBrowserHistory(browseCache.getUpdtime(), browseCache.getUrl());
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create();
                builder.show();
                return true;
            }
        });
    }

    @Override
    protected void initData() {
        loadData();
    }

    @Override
    protected boolean useLoadSir() {
        return true;
    }

    @Override
    protected Object registerTarget() {
        return refreshLayout;
    }

    @Override
    protected void onPageRetry(View v) {
        super.onPageRetry(v);
        loadData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_browser_history;
    }


    @Override
    public void onRightTxtClicked(View v) {
        super.onRightTxtClicked(v);
        if (mData.isEmpty()) {
            ToastUtil.showToast("暂无记录");
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(R.string.tmperson_confirm_clear_all)
                .setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPresenter.delAllBrowserHistory();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create();
        builder.show();

    }

    private void loadData() {
        BrowseDAO dao = new BrowseDAO(
                mAppComponent
                        .repositoryManager()
                        .obtainRealmConfig(DbConstant.DB_NAME)
        );
        mDisposable = dao.getBrowseCaches()
                .compose(RxUtils.<List<BrowseCache>>rxSchedulerHelper())
                .subscribeWith(new ResourceSubscriber<List<BrowseCache>>() {
                    @Override
                    public void onNext(List<BrowseCache> browseCaches) {
                        refreshLayout.finishRefresh();
                        mData.clear();
                        if (browseCaches != null) {
                            mData.addAll(browseCaches);
                        }
                        mAdapter.setListItems(mData);
                        if (mData.isEmpty()) {
                            showPageEmpty();
                        } else {
                            showPageContent();
                        }

                    }

                    @Override
                    public void onError(Throwable t) {
                        refreshLayout.finishRefresh();
                        showPageError();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    public void onDelSingle(Boolean b) {
        if (b) {
            mAdapter.getmListItems().remove(removePos);
            mAdapter.notifyItemRemoved(removePos);
            mAdapter.notifyItemRangeChanged(removePos, mAdapter.getmListItems().size());
            for (int i = 0; i < mAdapter.getmListItems().size(); i++) {
                if (i == mAdapter.getmListItems().size() - 1 && TextUtils.isEmpty(mAdapter.getmListItems().get(i).getUrl())) {
                    mAdapter.getmListItems().remove(i);
                    mAdapter.notifyItemRemoved(i);
                    mAdapter.notifyItemRangeChanged(i, mAdapter.getmListItems().size());
                } else {
                    if (TextUtils.isEmpty(mAdapter.getmListItems().get(i).getUrl())) {
                        if (!mAdapter.getmListItems().get(i).getTime().equals(mAdapter.getmListItems().get(i + 1).getTime())) {
                            mAdapter.getmListItems().remove(i);
                            mAdapter.notifyItemRemoved(i);
                            mAdapter.notifyItemRangeChanged(i, mAdapter.getmListItems().size());
                        }
                    }
                }
            }
            if (mData.isEmpty()) {
                showPageEmpty();
            }
            if (mAdapter.getmListItems().size() == 0) {
                showPageEmpty();
            }

        } else {
            ToastUtil.showToast("请求失败");
        }
    }

    @Override
    public void onDelAll(Boolean b) {
        if (b) {
            mData.clear();
            showPageEmpty();
        } else {
            ToastUtil.showToast("请求失败");
        }
    }


    @Override
    protected void onPause() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        super.onPause();
    }
}
